<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
  * Clase para visualizar y navegar por los distintos registros en la base de datos
  *
  * @autor  Andres Hocevar <aahahocevar@gmail.com>
  * @package controllers
  */
class dashboard extends CI_Controller {

/**
  * Página principal que se le muestra a los profesores
  *
  * Contiene información sobre las compañías y sus productos
  *
  * @return void
  */
	public function index(){
		$this->load->library('rapyd');

		$ut     = new rpd_auth_library();
		$rt     = $ut->logged(1);
		$id_int = $ut->id_int();
		if($rt===false) die('Acceso no permitido');

		$menu ='<div data-role="navbar"><ul>';
		$menu.='<li><a href="'.site_url('dashboard/index').'" data-transition="pop" class="ui-btn-active">Compa&ntilde;&iacute;as</a></li>';
		$menu.='<li><a href="'.site_url('dashboard/integ').'" data-transition="pop">Integrantes</a></li>';
		$menu.='<li><a href="'.site_url('dashboard/produ').'" data-transition="pop">Productos</a></li>';
		$menu.='<li><a href="'.site_url('dashboard/autco').'" data-transition="pop">Auto/Co Evaluaci&oacute;n</a></li>';
		$menu.='</ul></div>';

		$menu.= "<h3>Lista de compa&ntilde;&iacute;as registradas</h3>";
		$menu.= "<p>Seleccione la compa&ntilde;&iacute;a que desea evaluar</p>";
		$menu.= "<div class='content-primary'>
			<ul data-role='listview' data-filter='true'>";

		$sel=array('a.id','a.nombre','b.nombre AS producto');
		$this->db->select($sel);
		$this->db->from('compania AS a');
		$this->db->join('producto AS b','a.id_producto=b.id','left');
		$this->db->order_by('a.nombre','asc');
		$query = $this->db->get();

		$actis=array();
		if ($query->num_rows() > 0){
			foreach ($query->result() as $row){
				$prod = (empty($row->producto))?'No tiene producto asignado':$row->producto;
				$menu.= '<li><a href="'.site_url('dashboard/gcompania/'.$row->id).'">'.$row->nombre.' - '.$prod.'</a></li>';
			}
		}
		$menu.= "</ul></div>";

		$data['content']    = $menu;
		$data['footer']     = '<a href="'.site_url('/integrantes/modif/modify/'.$id_int).'" data-role="button" data-icon="gear" data-direction="reverse">Configurar cuenta</a>';
		$data['footer']    .= '<a href="'.site_url('/companias/dataeditmobil/create/').'" data-role="button" data-icon="add" data-direction="reverse">Agregar Compañía</a>';
		$data['footer']    .= '<a href="'.site_url('aucoevaluacion/reporte').'" data-role="button" data-icon="grid" data-direction="reverse" data-ajax="false">Reporte Notas</a>';
		$data['header']     = $this->_curso().'::Panel de control';
		$data['title']      = $this->_curso();
		$data['logout']     = true;
		$data['usuario']    = $ut->user('name');
		$data['headerextra']= 'Profesor: '.$ut->user('name');


		$this->load->view('view_ven', $data);
	}

/**
  * Lista de integrantes presentada a los profesoes
  *
  * Contiene información sobre todos los integrantes registrados
  *
  * @return void
  */
	public function integ(){
		$this->load->library('rapyd');

		$ut     = new rpd_auth_library();
		$rt     = $ut->logged(1);
		$id_int = $ut->id_int();
		if($rt===false) die('Acceso no permitido');

		$menu ='<div data-role="navbar"><ul>';
		$menu.='<li><a href="'.site_url('dashboard/index').'" data-transition="pop">Compa&ntilde;&iacute;as</a></li>';
		$menu.='<li><a href="'.site_url('dashboard/integ').'" data-transition="pop" class="ui-btn-active">Integrantes</a></li>';
		$menu.='<li><a href="'.site_url('dashboard/produ').'" data-transition="pop">Productos</a></li>';
		$menu.='<li><a href="'.site_url('dashboard/autco').'" data-transition="pop">Auto/Co Evaluaci&oacute;n</a></li>';
		$menu.='</ul></div>';

		$menu.= "<h3>Lista de integrantes</h3>";
		$menu.= "<p>Seleccione el integrante que desea gestionar</p>";
		$menu.= "<div class='content-primary'>
			<ul data-role='listview' data-filter='true'>";

		$sel=array('a.id AS id_compa','b.seccion','b.id','a.nombre AS compania','CONCAT_WS(\' \',b.nombre,b.apellido) AS nombre');
		$this->db->select($sel);
		$this->db->from('integrantes AS b');
		$this->db->join('compania AS a','b.id_compania=a.id','left');
		$this->db->order_by('b.seccion','asc');
		$this->db->order_by('b.nombre' ,'asc');
		$this->db->where('b.tipo','A');
		$query = $this->db->get();

		if ($query->num_rows() > 0){
			foreach ($query->result() as $row){
				$comp = (empty($row->id_compa))? 'No tiene compa&ntilde;ia asignada':$row->compania;
				$menu.= '<li><a href="'.site_url('dashboard/gintegrante/'.$row->id).'">'.$row->seccion.'-'.$row->nombre.'-'.$comp.'</a></li>';
			}
		}
		$menu.= "</ul></div>";


		$sel=array('b.id','CONCAT_WS(\' \',b.nombre,b.apellido) AS nombre');
		$this->db->select($sel);
		$this->db->from('integrantes AS b');
		$this->db->order_by('b.nombre','asc');
		$this->db->where('b.tipo' ,'P');
		$this->db->where('b.id <>',$id_int);
		$query = $this->db->get();
		if ($query->num_rows() > 0){
		$menu.= "<h3>Lista de profesores</h3>";
		//$menu.= "<p>Seleccione el integrante que desea gestionar</p>";
		$menu.= "<div class='content-primary'>
			<ul data-role='listview' data-filter='true'>";



			foreach ($query->result() as $row){
				$menu.= '<li><a href="'.site_url('integrantes/dataedit/modify/'.$row->id).'">'.$row->nombre.'</a></li>';
			}

			$menu.= "</ul></div>";
		}

		$data['content'] = $menu;
		$data['footer']  = '<a href="'.site_url('/integrantes/modif/modify/'.$id_int).'" data-role="button" data-icon="gear" data-direction="reverse">Configurar cuenta</a>';
		$data['footer'] .= '<a href="'.site_url('/integrantes/dataedit/create').'" data-role="button" data-icon="add" data-direction="reverse">Agregar Integrante</a>';
		$data['header']  = $this->_curso().'::Panel de control';
		$data['title']   = $this->_curso();
		$data['logout']  = true;
		$data['usuario'] = $ut->user('name');
		$data['headerextra']= 'Profesor: '.$ut->user('name');

		$this->load->view('view_ven', $data);
	}

/**
  * Lista de produtos que se le muestra a los profesores
  *
  * Contiene información sobre los productos registrados.
  *
  * @return void
  */
	public function produ(){
		$this->load->library('rapyd');

		$ut     = new rpd_auth_library();
		$rt     = $ut->logged(1);
		$id_int = $ut->id_int();
		if($rt===false) die('Acceso no permitido');

		$menu ='<div data-role="navbar"><ul>';
		$menu.='<li><a href="'.site_url('dashboard/index').'" data-transition="pop">Compa&ntilde;&iacute;as</a></li>';
		$menu.='<li><a href="'.site_url('dashboard/integ').'" data-transition="pop">Integrantes</a></li>';
		$menu.='<li><a href="'.site_url('dashboard/produ').'" data-transition="pop" class="ui-btn-active" >Productos</a></li>';
		$menu.='<li><a href="'.site_url('dashboard/autco').'" data-transition="pop">Auto/Co Evaluaci&oacute;n</a></li>';
		$menu.='</ul></div>';

		$menu.= "<h3>Lista de productos registrados</h3>";
		$menu.= "<p>Seleccione el producto que desea editar</p>";
		$menu.= "<div class='content-primary'>
			<ul data-role='listview' data-filter='true'>";

		$sel=array('b.id','b.nombre');
		$this->db->select($sel);
		$this->db->from('producto AS b');
		$this->db->order_by('b.nombre','asc');
		$query = $this->db->get();

		$actis=array();
		if ($query->num_rows() > 0){
			foreach ($query->result() as $row){
				$menu.= '<li><a href="'.site_url('producto/dataeditmobil/modify/'.$row->id).'">'.$row->nombre.'</a></li>';
			}
		}
		$menu.= "</ul></div>";

		$data['content'] = $menu;
		$data['footer']  = '<a href="'.site_url('/integrantes/modif/modify/'.$id_int).'" data-role="button" data-icon="gear" data-direction="reverse">Configurar cuenta</a>';
		$data['footer'] .= '<a href="'.site_url('/producto/dataeditmobil/create').'" data-role="button" data-icon="add" data-direction="reverse">Agregar Producto</a>';
		$data['header']  = $this->_curso().'::Panel de control';
		$data['title']   = $this->_curso();
		$data['logout']  = true;
		$data['usuario'] = $ut->user('name');
		$data['headerextra']= 'Profesor: '.$ut->user('name');

		$this->load->view('view_ven', $data);
	}

/**
  * Lista de las Auto y Co evaluaciones registradas
  *
  * Contiene información sobre las Auto y Co evaluaciones registradas
  *
  * @return void
  */
	public function autco(){
		$this->load->library('rapyd');
		$this->load->helper('date');

		$ut     = new rpd_auth_library();
		$rt     = $ut->logged(1);
		$id_int = $ut->id_int();
		if($rt===false) die('Acceso no permitido');

		$menu ='<div data-role="navbar"><ul>';
		$menu.='<li><a href="'.site_url('dashboard/index').'" data-transition="pop">Compa&ntilde;&iacute;as</a></li>';
		$menu.='<li><a href="'.site_url('dashboard/integ').'" data-transition="pop">Integrantes</a></li>';
		$menu.='<li><a href="'.site_url('dashboard/produ').'" data-transition="pop">Productos</a></li>';
		$menu.='<li><a href="'.site_url('dashboard/autco').'" data-transition="pop" class="ui-btn-active">Auto/Co Evaluaci&oacute;n</a></li>';
		$menu.='</ul></div>';

		$menu.= "<h3>Lista de Auto/Co evaluaciones planificadas</h3>";
		$menu.= "<p>Seleccionar para mayor detalle</p>";
		$menu.= "<div class='content-primary'>
			<ul data-role='listview' data-filter='true'>";

		$sel=array('a.fecha_inicio','a.comentario','a.plazo','a.id');
		$this->db->select($sel);
		$this->db->from('aucoevaluacion AS a');
		$this->db->order_by('a.fecha_inicio','desc');
		$query = $this->db->get();

		$actis=array();
		if ($query->num_rows() > 0){
			foreach ($query->result() as $row){
				$date = date_create($row->fecha_inicio);
				$fecha= date_format($date, 'd/m/Y');
				$intev= date_interval_create_from_date_string($row->plazo.' days');
				date_add($date,$intev);

				$ffinal = date_format($date, 'd/m/Y');
				//$menu.= '<li>'.$fecha.' - '.$ffinal.' '.$row->comentario.'</a></li>';
				$menu.= '<li><a href="'.site_url('aucoevaluacion/dataedit/modify/'.$row->id).'">'.$fecha.' - '.$ffinal.' '.$row->comentario.'</a></li>';
			}
		}
		$menu.= '</ul></div>';

		$data['content'] = $menu;
		$data['footer']  = '<a href="'.site_url('/integrantes/modif/modify/'.$id_int).'" data-role="button" data-icon="gear" data-direction="reverse">Configurar cuenta</a>';
		$data['footer'] .= '<a href="'.site_url('/aucoevaluacion/dataedit/create').'" data-role="button" data-icon="add" data-direction="reverse">Agregar</a>';
		$data['header']  = $this->_curso().'::Panel de control';
		$data['title']   = $this->_curso();
		$data['logout']  = true;
		$data['usuario'] = $ut->user('name');
		$data['headerextra']= 'Profesor: '.$ut->user('name');

		$this->load->view('view_ven', $data);
	}

/**
  * Método que genera el medidor
  *
  *
  * @param  float $val Valor a graficar, se asume que esta entre 0 y 100.
  * @return string
  */
	public function gauge($val=0){
		$this->load->library('dial_gauge',array('value'=>$val));
		header('Content-Type: image/png');
		$this->dial_gauge->display_png();
	}

/**
  * Método que permite evaluar el desempeño de la compañía
  *
  * @param  int $compania Clave primaria del registro en la tabla compania.
  * @return void
  */
	public function gcompania($compania){
		$this->load->library('rapyd');
		$ut= new rpd_auth_library();
		$rt=$ut->logged(1);
		if($rt===false) die('Acceso no permitido');

		$this->db->where('id', $compania);
		$this->db->from('compania');
		if($this->db->count_all_results()==0){
			redirect('dashboard');
		}

		$this->load->library('calendar');
		$this->load->helper('date');
		$this->load->helper('url');
		$this->load->helper('html');
		$this->load->helper('form');
		$conten=array();

		//Saca los integrates y producto
		$sel=array('a.nombre AS nombre','c.id AS idprod','c.nombre AS producto','c.descripcion','GROUP_CONCAT(b.nombre ORDER BY b.nombre) AS integrantes','GROUP_CONCAT(b.correo) AS correos');
		$this->db->select($sel);
		$this->db->from('compania AS a');
		$this->db->join('integrantes AS b','a.id=b.id_compania AND tipo=\'A\'','left');
		$this->db->join('producto AS c','a.id_producto=c.id','left');
		$this->db->where('a.id',$compania);
		$query = $this->db->get();
		$row = $query->row();

		$conten['role']       = 1;
		$conten['nombre']     =$row->nombre;
		$conten['integrantes']=$row->integrantes;
		$conten['producto']   =$row->producto;
		$conten['pnombre']    =$row->descripcion;
		$conten['correos']    =$row->correos;
		$idprod=$row->idprod;

		//Guarda la data
		$submit=$this->input->post('mysubmit');
		if($submit!==false){
			$compros = $this->input->post('cpr');
			if(!empty($compros)){
				foreach($compros as $id=>$avance){
					if(is_numeric($avance)){
						if($avance>100) $avance=100;
						$data = array('ejecucion' => $avance);

						$this->db->where('id', $id);
						$this->db->update('compromisos', $data);
					}
				}
			}

			$pro     = $this->input->post('promete');
			$dias    = $this->input->post('poster');
			$publica = $this->input->post('publica');

			if(!empty($pro)){
				$dias = ($dias>0)? $dias : 7;
				$body = "Se les informa a los accionistas los nuevos compromisos de la semana: \n";
				$prometes=explode("\n",$pro);
				$ffecha  = date('Y-m-d',mktime(0, 0, 0, date('m'), date('d')+$dias, date('Y')));
				foreach($prometes as $promesa){
					if(strlen($promesa)>2){
						if($publica=='1' && !empty($idprod)){
							$this->db->select(array('a.id AS id_compa'));
							$this->db->from('compania AS a');
							$this->db->where('a.id_producto',$idprod);
							$this->db->where('a.id <>',$compania);
							$query = $this->db->get();

							if ($query->num_rows() > 0){
								foreach ($query->result() as $itcomrow){
									$data = array(
										'id_compania' => $itcomrow->id_compa,
										'compromiso'  => $promesa,
										'ejecucion'   => 0,
										'id_producto' => (!empty($idprod))? $idprod : 0,
										'fecha'       => $ffecha
									);

									$this->db->insert('compromisos', $data);
								}
							}
						}
						$data = array(
							'id_compania' => $compania,
							'compromiso'  => $promesa,
							'ejecucion'   => 0,
							'id_producto' => (!empty($idprod))? $idprod : 0,
							'fecha'       => $ffecha
							);

						$this->db->insert('compromisos', $data);
						$body.="$promesa \n";

					}
				}
				//if(!empty($correos)){
				//	$this->_mail($correos,'GeRAIS:: Compromiso Semanal',$body);
				//}
			}
		}

		//Saca el promedio de avance
		$sel=array('AVG(ejecucion) AS prom');
		$this->db->select($sel);
		$this->db->from('compromisos');
		$this->db->where('id_compania',$compania);
		$this->db->where('fecha <= CURDATE()');
		$query = $this->db->get();
		$row   = $query->row();
		$conten['prom']  = round($row->prom,1);

		//Saca la salud
		$dbprefix=$this->db->dbprefix;
		$dbcompania=$this->db->escape($compania);
		$mSQL="SELECT VARIANCE(aa.prom) FROM
		(SELECT
		b.id AS id_integrante,
		IF(a.id IS NULL,0,SUM(a.ejecucion*a.peso)/SUM(a.peso)) AS prom
		FROM ${dbprefix}subcompromisos   AS a
		RIGHT JOIN ${dbprefix}integrantes AS b ON a.id_integrante=b.id
		WHERE b.id_compania=$dbcompania
		GROUP BY b.id)
		AS aa";
		$row   = $query->row();
		$conten['salud']  = round(sqrt($row->prom),1);

		//Saca los comrpomisos faltantes
		$sel=array('compromiso','ejecucion','fecha','id','UNIX_TIMESTAMP(fecha) AS uts');
		$this->db->select($sel);
		$this->db->from('compromisos');
		$this->db->where('id_compania',$compania);
		if(!empty($idprod) && $idprod>0)
			$this->db->where('id_producto',$idprod);
		$this->db->where('ejecucion <'  ,100);
		$this->db->order_by('fecha','asc');
		$this->db->order_by('id','asc');
		$query = $this->db->get();
		if ($query->num_rows() > 0){
			$conten['ecomprom']=$query->result();
		}else{
			$conten['ecomprom']=array();
		}

		//Saca los compromisos terminados
		$sel=array('compromiso','ejecucion','fecha','id','UNIX_TIMESTAMP(fecha) AS uts');
		$this->db->select($sel);
		$this->db->from('compromisos');
		$this->db->where('id_compania',$compania);
		if(!empty($idprod) && $idprod>0)
			$this->db->where('id_producto',$idprod);
		$this->db->where('ejecucion'  ,100);
		$this->db->order_by('fecha','desc');
		$this->db->order_by('id');
		$query = $this->db->get();
		if ($query->num_rows() > 0){
			$conten['comprom']=$query->result();
		}else{
			$conten['comprom']=array();
		}

		//Saca todos los informes ISA
		$sel=array('d.id AS integrante','d.seccion','b.id AS idcomp','b.compromiso','a.id','d.nombre','d.apellido','c.fecha');
		$this->db->select($sel);
		$this->db->from('subcomproresol AS a');
		$this->db->join('subcompromisos AS b','a.id_subcompromiso=b.id');
		$this->db->join('compromisos    AS c','b.id_compromisos=c.id'  );
		$this->db->join('integrantes    AS d','b.id_integrante=d.id'   );
		$this->db->where('c.id_compania',$compania);
		$this->db->order_by('d.id');
		$this->db->order_by('a.fecha','desc');
		//$this->db->order_by('a.id');
		$query = $this->db->get();
		if ($query->num_rows() > 0){
			$conten['isas']=$query->result();
		}else{
			$conten['isas']=array();
		}

		//Saca los compromisos de otros productos
		if(!empty($idprod) && $idprod>0){
			$sel=array('a.compromiso','a.ejecucion','a.fecha','a.id'
			,'UNIX_TIMESTAMP(a.fecha) AS uts','b.nombre AS prodnom');
			$this->db->select($sel);
			$this->db->from('compromisos AS a');
			$this->db->join('producto AS b','a.id_producto=b.id','left');
			$this->db->where('a.id_compania'   ,$compania);
			$this->db->where('a.id_producto <>',$idprod);
			$this->db->order_by('a.fecha','desc');
			$this->db->order_by('a.id');
			$query = $this->db->get();

			if ($query->num_rows() > 0){
				$conten['antcomprom']=$query->result();
			}else{
				$conten['antcomprom']=array();
			}
		}else{
			$conten['antcomprom']=array();
		}

		$conten['compania']   = $compania;

		$data['content']  = $this->load->view('view_gcompania',$conten,true);
		$data['back_url'] = 'dashboard/index';
		$data['header']   = 'Gerencia de Compa&ntilde;&iacute;a';
		$data['title']    = 'Gerencia de Compa&ntilde;&iacute;a';
		$data['footer']   = '<a href="'.site_url('companias/dataeditmobil/modify/'.$compania).'" data-role="button" data-icon="gear" data-direction="reverse">Editar Compañía</a>';
		$data['headerextra']= 'Profesor: '.$ut->user('name');

		$this->load->view('view_ven', $data);
	}

/**
  * Método que permite evaluar el desempeño de particular de un integrante
  *
  * @param  int $id_int Clave primaria del registro en la tabla integrante.
  * @return void
  */
	public function gintegrante($id_int){
		$this->load->library('rapyd');
		$ut= new rpd_auth_library();
		$rt=$ut->logged(1);
		if($rt===false) die('Acceso no permitido');

		$this->load->library('calendar');
		$this->load->helper('date');
		$this->load->helper('url');
		$this->load->helper('html');
		$this->load->helper('form');
		$conten=array();

		//Saca los integrates y producto
		$sel=array('a.nombre AS nombre','c.nombre AS producto','c.descripcion','CONCAT_WS(" ",b.nombre,b.apellido) AS integrantes','GROUP_CONCAT(b.correo) AS correos','a.id AS id_compania');
		$this->db->select($sel);
		$this->db->from('compania AS a');
		$this->db->join('integrantes AS b','a.id=b.id_compania AND tipo=\'A\'');
		$this->db->join('producto AS c','a.id_producto=c.id','left');
		$this->db->where('b.id',$id_int);
		$query = $this->db->get();
		$row = $query->row();

		$conten['nombre']     =$row->nombre;
		$conten['integrantes']=$row->integrantes;
		$conten['producto']   =$row->producto;
		$conten['pnombre']    =$row->descripcion;
		$conten['correos']    =$row->correos;
		$conten['id_compania']=$row->id_compania;

		//Saca el promedio de avance
		$sel=array('SUM(IF(b.ejecucion=100,100,a.ejecucion)*a.peso)/SUM(a.peso) AS prom');
		$this->db->select($sel);
		$this->db->from('subcompromisos AS a');
		$this->db->join('compromisos AS b','a.id_compromisos=b.id');
		$this->db->where('a.id_integrante',$id_int);
		$this->db->where('b.fecha <= CURDATE()');
		$query = $this->db->get();
		$row   = $query->row();
		$conten['prom']  = round($row->prom,1);

		//Saca las penalizaciones
		$sel=array('a.fecha','b.compromiso','a.exonerada','a.id');
		$this->db->select($sel);
		$this->db->from('penalizaciones AS a');
		$this->db->join('compromisos    AS b','a.id_compromisos=b.id');
		$this->db->where('a.id_integrante',$id_int);
		$this->db->order_by('fecha','desc');
		$this->db->order_by('id');
		$query = $this->db->get();
		if ($query->num_rows() > 0){
			$conten['penaliza']=$query->result();
		}else{
			$conten['penaliza']=array();
		}

		//Saca las evaluaciones
		$sel=array('resultado','fecha');
		$this->db->select($sel);
		$this->db->from('aucoevaluacion_it');
		$this->db->where('id_evaluado',$id_int);
		$this->db->order_by('fecha','desc');
		$this->db->order_by('id');
		$query = $this->db->get();
		if ($query->num_rows() > 0){
			$conten['evalu']=$query->result();
		}else{
			$conten['evalu']=array();
		}

		//Saca los compromisos faltantes
		$sel=array('a.compromiso','b.compromiso AS subcompromiso','b.peso',
				   'a.ejecucion' ,'b.ejecucion AS subejecucion'  ,
				   'b.fecha AS subfecha','b.id AS subid','c.id AS id_resol',
				   'a.fecha','a.id','UNIX_TIMESTAMP(a.fecha) AS uts');
		$this->db->select($sel);
		$this->db->from('compromisos    AS a');
		$this->db->join('subcompromisos AS b','b.id_compromisos=a.id');
		$this->db->join('subcomproresol AS c','c.id_subcompromiso=b.id AND c.reasignacion=a.reasignado','left');
		$this->db->where('b.id_integrante', $id_int);
		$this->db->order_by('a.fecha','desc');
		$this->db->order_by('a.id');
		$this->db->group_by('a.compromiso');
		$query = $this->db->get();
		//echo $this->db->last_query();
		if ($query->num_rows() > 0){
			$conten['ecomprom']=$query->result();
		}else{
			$conten['ecomprom']=array();
		}

		//Saca los isa
		$sel=array('a.compromiso','b.hiso','b.problema','b.promete','b.fecha','b.id','a.id AS idcomp');
		$this->db->select($sel);
		$this->db->from('subcompromisos AS a');
		$this->db->join('subcomproresol AS b','a.id=b.id_subcompromiso');
		$this->db->where('a.id_integrante',$id_int);
		$this->db->order_by('fecha','desc');
		$query = $this->db->get();

		if ($query->num_rows() > 0){
			$conten['isa']=$query->result();
		}else{
			$conten['isa']=array();
		}

		$conten['role']   = 1;
		$conten['id_int'] = $id_int;
		$data['content']  = $this->load->view('view_gintegrante',$conten,true);
		$data['back_url'] = 'dashboard/integ';
		$data['header']   = 'Gestión de integrantes';
		$data['title']    = 'Gestión de integrantes';
		$data['footer']   = '<a href="'.site_url('/integrantes/dataedit/modify/'.$id_int).'" data-role="button" data-icon="gear" data-direction="reverse">Editar Integrante</a>';
		$data['headerextra']= 'Profesor: '.$ut->user('name');

		$this->load->view('view_ven', $data);
	}

/**
  * Método que muestra información pertinente a los alumnos
  *
  * Muestra la lista de comrpomisos que debe cumplir el alumno junto
  * con los compromisos asociados a su empresa y la lista de isas registrados
  *
  * @return void
  */
	public function gcompalu(){
		$this->load->library('rapyd');
		$ut= new rpd_auth_library();
		$rt=$ut->logged();
		if($rt===false) die('Acceso no permitido');
		$id_int = $ut->id_int();
		$role   = $ut->role();

		$compania=$ut->id_comp();
		$this->load->library('calendar');
		$this->load->helper('date');
		$this->load->helper('url');
		$this->load->helper('html');
		$this->load->helper('form');
		$conten=array();
		$conten['role']=$role;

		//Saca los integrates y producto
		$sel=array('a.nombre AS nombre','c.nombre AS producto','c.descripcion'
		,'GROUP_CONCAT(b.nombre ORDER BY b.nombre) AS integrantes','GROUP_CONCAT(b.correo) AS correos'
		,'a.id_producto AS idprod');
		$this->db->select($sel);
		$this->db->from('compania AS a');
		$this->db->join('integrantes AS b','a.id=b.id_compania AND tipo=\'A\'');
		$this->db->join('producto AS c','a.id_producto=c.id','left');
		$this->db->where('b.id_compania',$compania);
		$query = $this->db->get();
		$row = $query->row();

		$conten['nombre']     =$row->nombre;
		$conten['integrantes']=$row->integrantes;
		$conten['producto']   =$row->producto;
		$conten['pnombre']    =$row->descripcion;
		$conten['correos']    =$row->correos;
		$idprod = $row->idprod;

		//Saca el promedio de avance
		$sel=array('AVG(ejecucion) AS prom');
		$this->db->select($sel);
		$this->db->from('compromisos');
		$this->db->where('id_compania',$compania);
		$this->db->where('fecha <= CURDATE()');
		$query = $this->db->get();
		$row   = $query->row();
		$conten['prom']  = round($row->prom,1);

		//Saca las tareas faltantes propios
		$sel=array('a.compromiso','b.compromiso AS subcompromiso',
				   'a.ejecucion' ,'b.ejecucion AS subejecucion'  ,
				   'b.fecha AS subfecha','b.id AS subid','c.id AS id_resol',
				   'a.fecha','a.id','UNIX_TIMESTAMP(a.fecha) AS uts');
		$this->db->select($sel);
		$this->db->from('compromisos    AS a');
		$this->db->join('subcompromisos AS b','b.id_compromisos=a.id');
		$this->db->join('subcomproresol AS c','c.id_subcompromiso=b.id AND c.reasignacion=a.reasignado','left');
		$this->db->where('a.id_compania'  , $compania);
		$this->db->where('a.ejecucion <'  , 100);
		if(!empty($idprod) && $idprod>0)
			$this->db->where('a.id_producto',$idprod);
		$this->db->where('b.id_integrante', $id_int);
		$this->db->order_by('a.fecha');
		$this->db->order_by('a.id');
		$query = $this->db->get();
		if ($query->num_rows() > 0){
			$conten['ecomprom']=$query->result();
		}else{
			$conten['ecomprom']=array();
		}

		//Saca los todos compromiso
		$sel=array('compromiso','ejecucion','fecha','id','UNIX_TIMESTAMP(fecha) AS uts');
		$this->db->select($sel);
		$this->db->from('compromisos');
		$this->db->where('id_compania',$compania);
		if(!empty($idprod) && $idprod>0)
			$this->db->where('id_producto',$idprod);
		$this->db->order_by('fecha');
		$this->db->order_by('id');
		$query = $this->db->get();

		if ($query->num_rows() > 0){
			$conten['comprom']=$query->result();
		}else{
			$conten['comprom']=array();
		}

		//Saca los isa
		$sel=array('a.compromiso','b.hiso','b.problema','b.promete','b.fecha','b.id','a.id AS idcomp');
		$this->db->select($sel);
		$this->db->from('subcompromisos AS a');
		$this->db->join('subcomproresol AS b','a.id=b.id_subcompromiso');
		$this->db->where('a.id_integrante',$id_int);
		$this->db->order_by('fecha');
		$query = $this->db->get();

		if ($query->num_rows() > 0){
			$conten['isa']=$query->result();
		}else{
			$conten['isa']=array();
		}
		$fecha=date('Y-m-d');
		$conten['compania']   = $compania;

		$this->db->select(array('a.id','a.fecha_inicio AS inicio','ADDDATE(a.fecha_inicio,plazo) AS final'));
		$this->db->from('aucoevaluacion AS a');
		$this->db->join('aucoevaluacion_it AS b','b.id_aucoevaluacion=a.id AND b.id_evaluador='.$this->db->escape($id_int),'left');
		$this->db->where('ADDDATE(a.fecha_inicio,plazo) >=',$fecha);
		$this->db->where('a.fecha_inicio <=',$fecha);
		$this->db->where('b.id IS NULL');
		$query = $this->db->get();

		if($query->num_rows() > 0){
			$itrow = $query->row();
			$conten['auco']  = '<p style="text-align:center;"><b>Desde el '.mdate('%d/%m/%Y', mysql_to_unix($itrow->inicio)).' hasta '.mdate('%d/%m/%Y', mysql_to_unix($itrow->final)).'</b><br />';
			$conten['auco'] .= '<a href="'.site_url('aucoevaluacion/ejecuta').'" data-role="button" data-icon="star" data-direction="reverse" data-theme="e">Auto/Co Evaluaci&oacute;n '.$itrow->id.'</a></p>';
		}

		//Saca todos los informes ISA restantes que no pertenecen al usuario
		$sel=array('d.id AS integrante','b.id AS idcomp','b.compromiso','a.id',
		"IF($id_int=d.id,'Tuyos',d.nombre) AS nombre",
		"IF($id_int=d.id,'',d.apellido) AS apellido",
		'c.fecha');
		$this->db->select($sel);
		$this->db->from('subcomproresol AS a');
		$this->db->join('subcompromisos AS b','a.id_subcompromiso=b.id');
		$this->db->join('compromisos    AS c','b.id_compromisos=c.id'  );
		$this->db->join('integrantes    AS d','b.id_integrante=d.id'   );
		$this->db->where('c.id_compania',$compania);
		$this->db->order_by('d.id');
		$this->db->order_by('a.fecha');
		$query = $this->db->get();
		if ($query->num_rows() > 0){
			$conten['isas']=$query->result();
		}else{
			$conten['isas']=array();
		}

		//Saca los compromisos de otros productos
		if(!empty($idprod) && $idprod>0){
			$sel=array('a.compromiso','a.ejecucion','a.fecha','a.id'
			,'UNIX_TIMESTAMP(a.fecha) AS uts','b.nombre AS prodnom');
			$this->db->select($sel);
			$this->db->from('compromisos AS a');
			$this->db->join('producto AS b','a.id_producto=b.id','left');
			$this->db->where('a.id_compania'   ,$compania);
			$this->db->where('a.id_producto <>',$idprod);
			$this->db->order_by('a.fecha','desc');
			$this->db->order_by('a.id');
			$query = $this->db->get();

			if ($query->num_rows() > 0){
				$conten['antcomprom']=$query->result();
			}else{
				$conten['antcomprom']=array();
			}
		}else{
			$conten['antcomprom']=array();
		}

		$conten['role']       = $role;
		$conten['id_compania']= $ut->id_comp();
		$data['content']  = $this->load->view('view_gcompalu',$conten,true);
		$data['header']   = $this->_curso().'::Gerencia de Compa&ntilde;&iacute;a';
		$data['title']    = 'Gerencia de Compa&ntilde;&iacute;a';
		$data['footer']   = '<a href="'.site_url('/integrantes/modif/modify/'.$id_int).'" data-role="button" data-icon="gear" data-direction="reverse">Configurar cuenta</a>';
		$data['home_url'] = '';
		$data['headerextra'] = ($role==1)? 'Profesor: ': (($role==2)? 'Alumno Gerente: ':'Alumno: ');
		$data['headerextra'].= $ut->user('name');

		$data['logout']   = true;
		$data['usuario'] = $ut->user('name');

		$this->load->view('view_ven', $data);
	}
/**
  * Método para evaluar la microgerencia por parte del profesor
  *
  * Permite darle porcentajes de avances y pesos a las tareas registradas,
  * adicionalmente permite registrar nuevas tareas y delegarlos a un integrante
  *
  *
  * @param  int $compromiso Clave primaria del registro en la tabla compromiso.
  * @return void
  */
	public function gsubcompania($compromiso){
		$this->load->library('rapyd');
		$ut= new rpd_auth_library();
		$rt=$ut->logged(1);
		if($rt===false) die('Acceso no permitido');
		$role   = $ut->role();

		$this->load->library('calendar');
		$this->load->helper('date');
		$this->load->helper('url');
		$this->load->helper('html');
		$this->load->helper('form');
		$conten=array();
		$conten['role']=$role;

		//Guarda la data
		$submit=$this->input->post('mysubmit');
		if($submit!==false){
			$compros=$this->input->post('cpr');
			$pesos  =$this->input->post('pes');
			if(!empty($compros)){
				foreach($compros as $id=>$avance){
					if(is_numeric($avance)){
						$data = array('ejecucion' => $avance);
						if(is_numeric($pesos[$id]) && $pesos[$id]>=1 && $pesos[$id]<=100) $data['peso'] = $pesos[$id];
						if($avance>100) $avance=100;

						$this->db->where('id', $id);
						$this->db->update('subcompromisos', $data);
					}
				}
			}

			$pro=$this->input->post('promete');
			if(!empty($pro)){
				$body="Se les informa a los accionistas los nuevos compromisos de la semana: \n";
				$prometes=explode("\n",$pro);
				foreach($prometes as $promesa){
					if(strlen($promesa)>2){
						$data = array(
							'id_compromisos' => $compromiso,
							'compromiso'     => $promesa,
							'peso'           => 1,
							'ejecucion'      => 0,
							'id_integrante'  => 0,
							'registro'       => 'P',
							'fecha'=>date('Y-m-d',mktime(0, 0, 0, date('m'), date('d')+7, date('Y')))
							);

						$this->db->insert('subcompromisos', $data);
						$body.="$promesa \n";
					}
				}
				//if(!empty($correos)){
				//	$this->_mail($correos,'GeRAIS:: Compromiso Semanal',$body);
				//}
			}
		}

		$sel=array('a.fecha','a.compromiso','a.id_compania'
			,'a.ejecucion','c.nombre','c.descripcion','c.id','b.nombre AS companianom');
		$this->db->select($sel);
		$this->db->from('compromisos AS a');
		$this->db->join('compania    AS b','a.id_compania=b.id');
		$this->db->join('producto    AS c','b.id_producto=c.id','left');
		$this->db->where('a.id',$compromiso);
		$query = $this->db->get();
		$row = $query->row();

		$conten['fecha']      = $row->fecha      ;
		$conten['compromiso'] = $row->compromiso ;
		$conten['ejecucion']  = $row->ejecucion  ;
		$conten['nombre']     = $row->nombre     ;
		$conten['descrip']    = $row->descripcion;
		$conten['id_comp']    = $compromiso      ;
		$conten['companianom']= $row->companianom;
		$id_compania          = $row->id_compania;
		$id_producto          = $row->id         ;
		$conten['id_compania']= $id_compania;

		//Saca los tareas
		$sel=array('a.compromiso','a.ejecucion','a.fecha','a.id','a.peso','MAX(c.id) AS idresol'
		,'UNIX_TIMESTAMP(a.fecha) AS uts','CONCAT_WS(\' \',nombre,apellido) AS nombre');
		$this->db->select($sel);
		$this->db->from('subcompromisos AS a');
		$this->db->join('integrantes    AS b','a.id_integrante   =b.id','left');
		$this->db->join('subcomproresol AS c','c.id_subcompromiso=a.id','left');
		$this->db->where('a.id_compromisos',$compromiso);
		$this->db->order_by('a.fecha','asc');
		$this->db->order_by('a.id','asc');
		$this->db->group_by('a.compromiso');
		$query = $this->db->get();

		if ($query->num_rows() > 0){
			$conten['ecomprom']=$query->result();
		}else{
			$conten['ecomprom']=array();
		}

		//Saca los tareas
		$sel=array('a.fecha','a.id','a.problema');
		$this->db->select($sel);
		$this->db->from('problemas AS a');
		$this->db->where('a.id_compromisos',$compromiso);
		$this->db->order_by('a.fecha','asc');
		$this->db->order_by('a.id');
		$query = $this->db->get();

		if ($query->num_rows() > 0){
			$conten['problemas']=$query->result();
		}else{
			$conten['problemas']=array();
		}

		$data['content']  = $this->load->view('view_gsubcompania',$conten,true);
		$data['back_url'] = 'dashboard/gcompania/'.$id_compania;
		$data['header']   = 'Sub-Gerencia de Compa&ntilde;&iacute;a';
		$data['title']    = 'Sub-Gerencia de Compa&ntilde;&iacute;a';
		$data['footer']   = '<a href="'.site_url('compromisos/dataeditmobil/modify/'.$compromiso).'" data-role="button" data-icon="gear" data-direction="reverse">Editar compromiso</a>';
		$data['footer']  .= '<a href="'.site_url('problemas/dataedit/'.$compromiso.'/create').'" data-role="button" data-icon="add" data-direction="reverse">Agregar Problema</a>';
		$data['headerextra'] = 'Profesor: ';
		$data['headerextra'].= $ut->user('name');

		$this->load->view('view_ven', $data);
	}

/**
  * Método para sub-delegar los compromisos por parte del alumno
  *
  * Permite darle pesos a las tareas registradas,
  * adicionalmente permite registrar nuevas tareas y delegarlos a un integrante
  *
  *
  * @param  int $compromiso Clave primaria del registro en la tabla compromiso.
  * @return void
  */
	public function gsubcompalu($compromiso){
		$this->load->library('rapyd');
		$ut= new rpd_auth_library();
		$rt=$ut->logged();

		if($rt===false) die('Acceso no permitido');
		$role  = $ut->role();
		if($role>2)     die('Acceso no permitido');

		$this->load->library('calendar');
		$this->load->helper('date');
		$this->load->helper('url');
		$this->load->helper('html');
		$this->load->helper('form');
		$conten=array();
		$conten['role']=$role;

		$sel=array('a.fecha','a.compromiso','a.id_compania','a.ejecucion','c.nombre','c.descripcion','c.id');
		$this->db->select($sel);
		$this->db->from('compromisos AS a');
		$this->db->join('compania    AS b','a.id_compania=b.id');
		$this->db->join('producto    AS c','b.id_producto=c.id','left');
		$this->db->where('a.id',$compromiso);
		$query = $this->db->get();
		$row = $query->row();

		$conten['fecha']      = $row->fecha      ;
		$conten['compromiso'] = $row->compromiso ;
		$conten['ejecucion']  = $row->ejecucion  ;
		$conten['nombre']     = $row->nombre     ;
		$conten['descrip']    = $row->descripcion;
		$conten['id_comp']    = $compromiso;
		$id_compania          = $row->id_compania;
		$id_producto          = $row->id;

		//Saca las tareas
		$sel=array('a.compromiso','a.ejecucion','a.fecha','a.id','a.peso'
		,'UNIX_TIMESTAMP(a.fecha) AS uts','CONCAT_WS(\' \',nombre,apellido) AS nombre');
		$this->db->select($sel);
		$this->db->from('subcompromisos AS a');
		$this->db->join('integrantes AS b','a.id_integrante=b.id','LEFT');
		$this->db->where('a.id_compromisos',$compromiso);
		$this->db->order_by('a.fecha','asc');
		$this->db->order_by('a.id','asc');
		$query = $this->db->get();

		if ($query->num_rows() > 0){
			$conten['ecomprom']=$query->result();
		}else{
			$conten['ecomprom']=array();
		}

		$conten['id_compania']= $ut->id_comp();
		$data['content']    = $this->load->view('view_gsubcompalu',$conten,true);
		$data['back_url']   = 'dashboard/gcompalu';
		$data['home_url']   = 'dashboard/gcompalu';
		$data['header']     = 'Sub-Gerencia de Compa&ntilde;&iacute;a';
		$data['title']      = 'Sub-Gerencia de Compa&ntilde;&iacute;a';

		$date_compr = new DateTime($conten['fecha']);
		$date_ahora = new DateTime();

		if($conten['ejecucion']<100 && $date_compr>=$date_ahora){
			$data['footer']   = '<a href="'.site_url('subcompromisos/dataeditmobil/'.$compromiso.'/create').'" data-role="button" data-icon="add" data-direction="reverse">Agregar Tarea</a>';
		}else{
			$data['footer']   = '';
		}
		$data['headerextra'] = ($role==1)? 'Profesor: ': (($role==2)? 'Alumno Gerente: ':'Alumno: ');
		$data['headerextra'].= $ut->user('name');

		$this->load->view('view_ven', $data);
	}

/**
  * Método para optener el curso
  *
  *
  * @return string
  */
	function _curso(){
		$sel=array('nombre');
		$this->db->select($sel);
		$this->db->from('curso AS a');
		$this->db->limit(1);
		$query = $this->db->get();

		if ($query->num_rows() > 0){
			$row    = $query->row();
			$nombre = $row->nombre;
		}else{
			$nombre = 'No hay información del curso';
		}

		return $nombre;
	}
}
